  // 调试采购管理--基础数据===项目
<template>
  <PageTemplate>
    <div class="pur" slot="content">
      <el-form
        inline
        :model="query"
        ref="query"
        label-position="right"
        label-width="82px"
        class="search-collapse-pro-form"
      >
        <SearchCollapsePro>
          <div slot="title" class="search-collapse-pro-title">
            <el-form-item label-width="0px">
              <el-input v-model="query.projectCode" :placeholder="$t('pur.project_code')">
                <el-button slot="append" icon="el-icon-search" @click="queryDataTableLike"></el-button>
              </el-input>
            </el-form-item>
          </div>
          <div slot="collapse">
            <!-- 高级搜索具体内容 -->
            <el-form-item :label="$t('pur.project_name')" prop="projectName">
              <el-input v-model="query.projectName"></el-input>
            </el-form-item>
            <!-- 查询和重置按钮-->
            <el-row :gutter="10">
              <div class="btn-group-search">
                <el-col :span="2">&nbsp;</el-col>
                <el-col :span="6">
                  <el-button
                    type="primary"
                    class="btn-default"
                    @click="getAllDataTable"
                    size="small"
                  >{{$t('cm.query')}}</el-button>
                  <el-button
                    class="btn-second"
                    @click="queryReset('query')"
                    style="margin:0;"
                    size="small"
                  >{{$t('cm.reset')}}</el-button>
                </el-col>
              </div>
            </el-row>
          </div>
        </SearchCollapsePro>
      </el-form>
      <el-row class="row-empty-20"></el-row>
      <PageTableCollapse :collapseStatus="true">
        <el-row slot="title">
          <!-- <el-col :span="12"><div style="line-height: 40px"> {{$t('pur.table_title')}} </div></el-col> -->
          <el-col>
            <!-- style="float:right;" -->
            <div>
              <el-button type="primary" @click="add" v-if="showBtn">
                <i class="el-icon-edit"></i> {{$t('cm.add')}}
              </el-button>
              <el-button type="primary" @click="deleteBatch" v-if="showBtn && isSys ==='true'">
                <i class="el-icon-delete"></i> {{$t('cm.delete')}}
              </el-button>
              <el-button type="primary" @click="exportExcel">
                <i class="el-icon-download"></i> {{$t('cm.export')}}
              </el-button>
              <el-button type="primary" @click="openImport">
                <i class="el-icon-upload2"></i> {{$t('cm.import')}}
              </el-button>
            </div>
          </el-col>
        </el-row>
        <el-table
          class="table"
          border
          ref="multipleTable"
          :data="tables"
          tooltip-effect="dark"
          style="width: 100%"
          :show-overflow-tooltip="true"
          @selection-change="handleSelectionChange"
          :header-cell-style="{background:tableHeaderBGC}"
        >
          <el-table-column align="center" type="selection" width="60"></el-table-column>
          <el-table-column type="index" :label="$t('cm.no')" align="center" width="60"></el-table-column>
          <el-table-column prop="projectCode" :label="$t('pur.project_code')" align="center"></el-table-column>
          <el-table-column prop="projectName" :label="$t('pur.project_name')" align="center"></el-table-column>
          <el-table-column prop="isValid" :label="$t('cm.is_valid')" align="center" :formatter="formatTableText"></el-table-column>
          <el-table-column prop="description" :label="$t('pur.project_description')" align="center"></el-table-column>
          <el-table-column :label="$t('cm.operate')" align="center" v-if="isSys ==='false'">
            <template slot-scope="scope">
              <ListBtnSys :options="sysbtns" :is-sys='isSys' :row-data="scope.row" @triggerListBtn="handleListBtn" :show-btn="showBtn"></ListBtnSys>
            </template>
          </el-table-column> 
          <el-table-column :label="$t('cm.operate')" align="center" v-if="isSys ==='true'">
            <template slot-scope="scope">
              <ListBtn :options="btns" :row-data="scope.row" @triggerListBtn="handleListBtn" :show-btn="showBtn"></ListBtn>
            </template>
          </el-table-column>
        </el-table>
        <div class="block pager-customer">
          <el-pagination
            background
            layout="total,prev,pager, next,jumper"
            :current-page.sync="pagingCurrentPageNum"
            :page-sizes="pagingPageSizes"
            :page-size="pagingPageSize"
            :total="pagingTotal"
            @size-change="pagingHandleSizeChange"
            @current-change="pagingHandleCurrentChange"
          >
          </el-pagination>
        </div>
      </PageTableCollapse>
      <!-- 导入 -->
      <el-dialog :visible.sync="dialogImportVisible" width="732px">
        <el-form label-width="120px">
          <el-row>
            <div style="text-align: center; margin-bottom: 10px;">
              <a @click="downCardTemplate" style="cursor: pointer;">模板下载</a>
            </div>
          </el-row>
          <el-row>
            <el-col :span="24" style="text-align:center;">
              <div>
                <el-upload
                  class="upload-demo"
                  drag
                  :http-request="uploadCardTemplate"
                  action
                  ref="cardupload"
                  :on-remove="handleTemplateRemove"
                  :on-success="handleTemplateSuccess"
                  :before-upload="beforeTemplateUpload"
                  :on-progress="handleTemplateProgress"
                  name="file"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                </el-upload>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogImportVisible = false">取 消</el-button>
        </div>
        <div slot="title" class="dialog-edit-head">
          <i>导入</i>
        </div>
      </el-dialog>
      <!-- 导入 end-->
    </div>
  </PageTemplate>
</template>
<style lang="scss">
</style>
<script>
import { mapState, mapActions, mapGetters } from 'vuex'
import PageTemplate from '@/components/common/PageTemplate'
import PageTableCollapse from '@/components/common/PageTableCollapse'
import SearchCollapsePro from '@/components/common/SearchCollapsePro'
import ListBtn from '@/components/btn/ListBtn'
import { ALERT } from '@/utils/responseHandle'
import * as Constant from '@/utils/constant'
import {COMMON} from '@/utils/commonUtil'
import {dateFtt} from '@/utils/datetime'
import Pagination from '@/mixins/Pagination'
import HasBtn from '@/mixins/HasBtn'
import api_pur from '@/api/api_pur'
import ListBtnSys from '@/components/btn/ListBtnSys'
import { getUserRoles } from '@/api/api.js'
export default {
  components: { PageTemplate, PageTableCollapse, SearchCollapsePro, ListBtn, ListBtnSys },
  data () {
    return {
      query: {
        projectCode: null,
        projectName: null
      },
      tables:[],
      btns: [
        {
          value: 'edit',
          label: 'cm.edit'
        },
        {
          value: 'del',
          label: 'cm.delete'
        }
      ],
      sysbtns: [
        {
          value: 'edit',
          label: 'cm.edit',
          isdba: 'false'
        },
        {
          value: 'del',
          label: 'cm.delete',
          isdba: 'false'
        }
      ],
      isSys: '',
      dialogImportVisible: false,
      fileList: []
    }
  },
  created () {
    this.getAllDataTable()
    this.getNowUserRole()
  },
  mixins: [Pagination, HasBtn],
  watch: {
  },
  methods: {
    ...mapActions('common', [
      'queryCollapse'
    ]),
    getNowUserRole(){
      let _this = this;
      getUserRoles({}).then((result) => {
        if (result.status == "200" && result.data.code == "0") {  
          let dataList = result.data.data
          // sysadmin 系统管理员
          const isAdmin = dataList.some(item => item ==='sysadmin')
          console.log('===isAdmin:',isAdmin)
          if(isAdmin){
            _this.isSys= 'true'
          }else{
            _this.isSys= 'false'
          }
      //console.log("deptNamePath",result.data.data.deptNamePath);
        } else {
          _this.$alert(result.data.msg, _this.$t('cm.tips'));
        }
      }).catch((err) => {
        _this.$alert(err,_this.$t('cm.tips'));
      });
    },
    exportExcel () {
      let fileName = `基础数据_项目_${dateFtt('yyyy-MM-dd', new Date())}`
      api_pur.purProjectExport(this.query, response => {
        if (response.code === Constant.RT_SUCCESS) {
          // 导出Excel完成后，清除勾选
          this.$refs.multipleTable.clearSelection()
          COMMON.downloadLinkByUrl(response.data.webRequestUrl, fileName)
        } else {
          ALERT.alertResp(response)
        }
      })
    },
    //导出excel之前,勾选id
    handleSelectionChange(val) {
      this.multipleSelection = val
      //console.log("======2021-10-08----215===val==--",val);
      this.query.ids = [];
      val.forEach(item => {
        this.query.ids.push(item.id);
      });
    },
    //重置操作
    queryReset (formName) {
      this.$refs[formName].resetFields()
    },
    queryDataTableLike () {
      this.getAllDataTable()
    },
    getAllDataTable () {
      this.queryTableList({
        ...this.query,
        pageNum: this.pagingCurrentPageNum,
        pageSize: this.pagingPageSize
      })
    },
    //统一与后台操作的方法
    queryTableList (params) {
      //这里的params是对象
      //注意 如果后台json转对象 时间类型好像会抛异常  转到后台 前台用 qs 来转换数据 设置一个全局拦截器 main.js 参考
      let _this = this
      let tables = []
      let totalCount = 0
      api_pur.purProjectLoadByPaging(params, result => {
        if (result.code === Constant.RT_SUCCESS) {
          //表格数据  数组            
          tables = result.data.results
          //分页数据
          totalCount = result.data.totalRows
        } else {
          // _this.$t('cm.tips')
          ALERT.error(result.data.msg)
        }
        _this.setPagingTotal(totalCount)
        this.tables = tables
      })
    },
    add () {
      COMMON.routerTo(Constant.ROUTE_PUR_BAS_PROJECT_EDIT.index, this.$router, { id: Constant.NEW_PARAMS })
    },
    edit (row) {
      COMMON.routerTo(Constant.ROUTE_PUR_BAS_PROJECT_EDIT.index, this.$router, { id: row.id })
    },
    del (row) {
      COMMON.confirm({}, () => {
        this.doDelete([row.id])
      })
    },
    deleteBatch () {
      if (this.multipleSelection.length > 0) {
        COMMON.confirm({}, () => {
          var ids = this.multipleSelection.map(item => item.id)
          this.doDelete(ids)
        })
      } else {
        ALERT.warn('请选择数据')
      }
    },
    doDelete (ids) {
      api_pur.purProjectDelete({ids}, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.getAllDataTable()
          ALERT.success(result.msg)
        } else {
          ALERT.error(result.msg)
        }
      })
    },
    formatTableText (row, column, cellValue, index) {
      var fmtValue = null
      if (column.property === 'isValid') {
        fmtValue = this.isValidMap[row.isValid]
      }
      return fmtValue !== null && fmtValue !== undefined ? fmtValue : cellValue
    },
    // 导入
    openImport () {
      this.dialogImportVisible = true
    },
    downCardTemplate () {
      COMMON.downloadLinkByUrl('/static/xlsx/template_excel_import_PurchaseProject.xlsx', '项目模板.xlsx')
    },
    uploadCardTemplate (fileObj) {
      api_pur.purProjectImport(fileObj, response => {
        if (response.code === Constant.RT_SUCCESS) {
          fileObj.onProgress({ percent: 100 })
          setTimeout(() => {
            fileObj.onSuccess(response, fileObj)
          }, 200)
        } else {
          ALERT.errorDefault(response)
        }
        this.fileList = []
        COMMON.hideLoading()
      })
    },
    beforeTemplateUpload (file) {
      let fileType = file.name.split('.').pop()
      const isXLSX = fileType === 'xlsx' || fileType === 'xls'
      if (!isXLSX) {
        this.$message.warning('导入模板文件类型不正确，请下载模板进行修改')
        return false
      }
      return true
    },
    handleTemplateRemove (file, fileList) {
      this.fileList = fileList
    },
    handleTemplateSuccess (res, option) {
      ALERT.success('导入成功！')
      this.fileList = []
      this.getAllDataTable()
    },
    handleTemplateProgress (event, file, fileList) {
      if (event.percent === 100) {
        this.dialogImportVisible = false
        COMMON.showLoading('正在导入中...')
      }
    }
  },
  mounted () {
  },
  computed: {
    ...mapState({
      tableHeaderBGC: state => state.common.tableHeaderBGC
    }),
    ...mapGetters({
      isValidMap: 'dict/isValidMap'
    })
  }
}
</script>